package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param articleId
     */
    @Override
    public void buildArticleToMinIO(Long articleId)  {
        //1.获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if(apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())){
            //2.通过freemarker生成html文件
            InputStream in = null;
            try {
                Template template  = configuration.getTemplate("article.ftl");
                //合成
                Map<String,Object> map = new HashMap<>();
                map.put("content", JSONArray.parseArray(apArticleContent.getContent()));
                StringWriter out = new StringWriter();

                template.process(map,out);

               in = new ByteArrayInputStream(out.toString().getBytes());

            } catch (Exception e) {
                e.printStackTrace();
                log.info("生成文章详情页面失败");
            }

            //3.上传到minio
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", in);

            //4.修改ap_article 中的static_url
            ApArticle apArticle = new ApArticle();
            apArticle.setId(apArticleContent.getArticleId());
            apArticle.setStaticUrl(path);

            apArticleMapper.updateById(apArticle);

        }
    }
}
